package com.lx.pc.restful.usercookie;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;

import com.lx.pc.domain.vo.user.UserCookieQo;
import com.lx.pc.domain.vo.user.UserVo;
import com.lx.pc.restful.util.SystemEnums;

public class UserCookie {

	public static String getIpAddr(HttpServletRequest request) {
	    String ip = request.getHeader("X-Real-IP");
	    if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
	            return ip;
	    }
	    ip = request.getHeader("X-Forwarded-For");
	    if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {
		    // 多次反向代理后会有多个IP值，第一个为真实IP。
		    int index = ip.indexOf(',');
		    if (index != -1) {
		           return ip.substring(0, index);
		    } else {
		           return ip;
		    }
	    } else {
	           return request.getRemoteAddr();
	    }
	}
	
	/**
	 * 保存用户登录cookie
	 * 
	 */
	/*public  void addUserInfoCookie(HttpServletResponse response, UserVo userInfo){
		String name = SystemEnums.Project.LVXIA_FRONT_WEB.getCode() + "_USER_ID";
		String id = userInfo.getbId();
		String userName = userInfo.getUserName();
		String password = userInfo.getPassword();
		//String lastLoginTime = String.valueOf(System.currentTimeMillis());//String.valueOf(userInfo.getLastLoginTime().getTime());
		UserCookieQo userCookieQo = new UserCookieQo();
		userCookieQo.setId(String.valueOf(id));
		userCookieQo.setUserName(userName);
		userCookieQo.setPassword(password);
		//userCookieQo.setLastLoginTime(lastLoginTime);
		String value = JsonUtils.toJson(userCookieQo);
	    Cookie cookie = new Cookie(name, value);
	    cookie.setPath("/");
	    cookie.setMaxAge(365*24*60*60);
	    response.addCookie(cookie);
	}*/
	
	public void addUserInfoCookie(HttpServletRequest request,HttpServletResponse response, UserVo userInfo){
		String nameCode = SystemEnums.Project.LVXIA_FRONT_WEB.getCode() + "_USER_ID";
		String userName = userInfo.getUserName();
		String password = userInfo.getPassword();
		String id = userInfo.getbId();
		String ip = getIpAddr(request);
        String value = ip+ "-&&&&"+userName+"-&&&&"+password+"-&&&&"+id;
	    UserCookie cookie = new UserCookie();
	    cookie.addCookie(response, nameCode, value);
	}
	
	/**
	 * 获取用户登录cookie
	 * 
	 */
	public UserCookieQo getUserInfoCookie(HttpServletRequest request){
		UserCookieQo userCookieQo = new UserCookieQo();
		String name = SystemEnums.Project.LVXIA_FRONT_WEB.getCode() + "_USER_ID";
		Map<String,Cookie> cookieMap = ReadCookieMap(request);
		if (cookieMap.containsKey(name)) {
			Cookie cookie = (Cookie)cookieMap.get(name);
			String usrpwd=cookie.getValue();
			String[] s1=usrpwd.split("-&&&&",4);
			String id=s1[3];
			userCookieQo.setId(id);
		}
		return userCookieQo;
	}
	
	/**
	 * 添加cookie
	 * @param response
	 * @param name
	 * @param value
	 */
    public  void addCookie(HttpServletResponse response,String name,String value){
        //例如：
        Cookie cookie = new Cookie(name,value);
        cookie.setPath("/");
        cookie.setMaxAge(365*24*60*60);
        response.addCookie(cookie);
    }
    
	/**
	 * 删除cookie
	 * 
	 * @param response
	 * @param name
	 */
	public static void removeCookie(HttpServletResponse response) {
		String name = SystemEnums.Project.LVXIA_FRONT_WEB.getCode() + "_USER_ID";
		Cookie uid = new Cookie(name, null);
		uid.setPath("/");
		uid.setMaxAge(0);
		response.addCookie(uid);
	}

    /**
     * 根据名字获取cookie
     * @param request
     * @param name cookie名字
     * @return
     */
    public Cookie getCookieByName(HttpServletRequest request,String name){
        Map<String,Cookie> cookieMap = ReadCookieMap(request);
        if(cookieMap.containsKey(name)){
            Cookie cookie = (Cookie)cookieMap.get(name);
            return cookie;
        }else{
            return null;
        }   
    }
     
    /**
     * 将cookie封装到Map里面
     * @param request
     * @return
     */
    private static Map<String,Cookie> ReadCookieMap(HttpServletRequest request){  
        Map<String,Cookie> cookieMap = new HashMap<String,Cookie>();
        Cookie[] cookies = request.getCookies();
        if(null!=cookies){
            for(Cookie cookie : cookies){
                cookieMap.put(cookie.getName(), cookie);
            }
        }
        return cookieMap;
    }

}
